package com.zhangfb95.crosschain.protocol.exc;

import com.zhangfb95.crosschain.infra.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author zhangfubing
 * @since 2023/12/12
 */
@Slf4j
public class ExcServiceRegistry {

    private final Map<String, ExcService> excServiceMap = new ConcurrentHashMap<>();

    public void register(String url, ExcService pluginService) {
        excServiceMap.put(url, pluginService);
    }

    public ExcAccountService getExcAccountService(String url) {
        return getExcService(url).getExcAccountService();
    }

    public ExcChainService getExcChainService(String url) {
        return getExcService(url).getExcChainService();
    }

    public Map<String, ExcChainService> getExcChainServices() {
        return excServiceMap.entrySet().stream().collect(Collectors.toMap(
                Map.Entry::getKey,
                excService -> excService.getValue().getExcChainService()
        ));
    }

    private ExcService getExcService(String url) {
        ExcService excService = excServiceMap.get(url);
        if (excService == null) {
            String errMessage = "can not get excService, url:" + url;
            log.error(errMessage);
            throw new BusinessException(errMessage);
        }
        return excService;
    }
}
